﻿namespace Paw.Phone.Pages
{
    using System.Windows;
    using System.Windows.Navigation;
    using Microsoft.Phone.Controls;
    using Microsoft.Phone.Shell;
    using Microsoft.Phone.Tasks;
    using Paw.Phone.ViewModel;

    public partial class UploadPhotoPage : PhoneApplicationPage
    {
        public UploadPhotoPage()
        {
            this.InitializeComponent();

            this.ViewModel = new UploadPhotoPageViewModel();
        }

        public UploadPhotoPageViewModel ViewModel
        {
            get { return this.DataContext as UploadPhotoPageViewModel; }
            set { this.DataContext = value; }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            var photoResult = GetApplicationState<PhotoResult>("PhotoResult");
            if ((this.ViewModel != null) && (photoResult != null))
            {
                this.ViewModel.LoadPhoto(photoResult);
            }
            else
            {
                this.NavigationService.GoBack();
            }
        }

        private static T GetApplicationState<T>(string key)
        {
            if (!PhoneApplicationService.Current.State.ContainsKey(key))
            {
                return default(T);
            }

            return (T)PhoneApplicationService.Current.State[key];
        }

        private void OnUploadPicture(object sender, RoutedEventArgs e)
        {
            if (this.ViewModel != null)
            {
                if (string.IsNullOrEmpty(this.ViewModel.BlobName))
                {
                    MessageBox.Show("The blob name cannot be null nor empty.", "Upload Photo Result", MessageBoxButton.OK);
                }
                else
                {
                    this.ViewModel.UploadPhoto(
                        (successMessage) =>
                        {
                            this.Dispatcher.BeginInvoke(
                        () =>
                        {
                            MessageBox.Show(successMessage, "Upload Photo Result", MessageBoxButton.OK);
                            PhoneApplicationService.Current.State.Remove("PhotoResult");
                            this.NavigationService.GoBack();
                        });
                        },
                        (errorMessage) =>
                        {
                            this.Dispatcher.BeginInvoke(
                                () =>
                                {
                                    MessageBox.Show(errorMessage, "Upload Photo Result", MessageBoxButton.OK);
                                });
                        });
                }
            }
        }
    }
}